<?php
ob_start();
session_start();

mysql_connect('localhost', 'root', 'at!admin');
mysql_select_db('netflix_db');
	
require_once('../FirePHPCore/fb.php');
require_once('NetflixQueue.php');
require_once('Netflix.php');
require_once('NetflixQueueItem.php');

function showLogin(){
?><p>Choose a username<br />
	<form method="POST" action="?action=login" >
		<input type="text" name="username" /><br/>	
		<button type="submit">Login / Register</button>
	</form>
</p><?php
}


function showMenu(){
	?>
	<form method="POST" action="?action=search_title" >
		<input type="text" name="title" value="Charlie Wilson's War"/><br/>	
		<button type="submit">Search For Title</button>
	</form>
	
	<form>
		After access token, click here to list your details: 
		<input type="submit" name="action" value="user_details" />
	</form>
	
	<form>
		After getting access token, click here to list your feeds: 
		<input type="submit" name="action" value="user_feeds" />
	</form>
	
	<form>
		After access token, click here to list your queues: 
		<input type="submit" name="action" value="user_queues" />
	</form>
	
	<form>
		After access token, click here to list your disc queue: 
		<input type="submit" name="action" value="list_queue" /><br />
	<!--	Name for queue:<input type="text" name="queue_name" /> -->
	</form>
	
	<form>
		After access token, click here to pop the top of your disc queue: 
		<input type="submit"name="action" value="pop_disc_queue" />
	</form>
	<?php
}

function beginRegistration($username){
	if(strlen($username) == 0){
		echo "Empty usernames are not allowed.<br />";
		return;
	}
	
	$_SESSION['username'] = $username;
	$netflix = getNetflix();	
	if($netflix != null){
		if(!isset($_SESSION['oauth_token'])){
			$token = $netflix->getRequestToken();
			$_SESSION['oauth_token'] = $token->key;
			$_SESSION['oauth_token_secret'] = $token->secret;
			fb($token, 'request token:');
		}

		$netflix->authorizeRequestToken($_SESSION['oauth_token']); //sends user to netflix. user will return from netflix to access_token
	}
	else{
		echo "Could not get a netflix object in beginRegistration($username)<br />";
	}
}


function doPOST(){
	$action = null;
	
	if(array_key_exists('action', $_REQUEST)){
		$action = $_REQUEST['action'];
	}
	
	if($action == 'reset'){
		foreach($_SESSION as $key => $value){
			unset($_SESSION[$key]);
		}
		return;
	}
	
	else if ($action == "search_title"){
		$search_term = $_REQUEST['title'];
		if($search_term){
			$netflix = getNetflix($_SESSION['username'], $_SESSION['access_token'], $_SESSION['access_token_secret'], $_SESSION['netflix_user_id']);
			$xml = $netflix->searchByTitle($search_term);
			if($xml){
				$dom = new SimpleXMLElement($xml);
				foreach($dom->catalog_title as $catalog_title){
					$urlXpathResults = $catalog_title->xpath('./link[@rel = \'alternate\']/@href');
					$url = reset($urlXpathResults);
					echo "<a href='$url' target='_blank'>{$catalog_title->title['regular']}</a><br />";
	/* 				$netflix->getUserQueueDisc()->enqueue($catalog_title->id);  //Adds the resultant movies to the user's queue */
				}
			}
		}
	}
	else if ($action == "user_details") {
		$netflix = getNetflix($_SESSION['username'], $_SESSION['access_token'], $_SESSION['access_token_secret'], $_SESSION['netflix_user_id']);
		$xml = $netflix->getUserDetails();
		if($xml != NULL){
			$xml = new SimpleXMLElement($xml);
			echo "User's name is " . $xml->first_name . " " . $xml->last_name;
			echo "<br />User id is " . $netflix->getUserId() . "<br />";
		}
	}
	
	else if ($action == "user_queues") {
		$netflix = getNetflix($_SESSION['username'], $_SESSION['access_token'], $_SESSION['access_token_secret'], $_SESSION['netflix_user_id']);
		$feed_contents = $netflix->getUserQueues();
		if($feed_contents){
			$feed_contents = new SimpleXMLElement($feed_contents);
			print_r($feed_contents);
		}
	}
	else if ($action == "list_queue") {
		$netflix = getNetflix($_SESSION['username'], $_SESSION['access_token'], $_SESSION['access_token_secret'], $_SESSION['netflix_user_id']);
		$queue = $netflix->getUserQueueDisc();

		echo $queue->toString();
	}
	else if ($action == "user_feeds") {
		$netflix = getNetflix($_SESSION['username'], $_SESSION['access_token'], $_SESSION['access_token_secret'], $_SESSION['netflix_user_id']);
	    $feed_contents = $netflix->getUserFeeds();
		if($feed_contents){
			$feed_contents = new SimpleXMLElement($feed_contents);
			foreach($feed_contents->xpath("/resource/link") as $link){
				$title = $link['title'];
				$href = $link['href'];
				echo "<br/><a href=\"$href\">$title</a>";
			}
		}
	}	
	else if ($action== "pop_disc_queue"){
		$netflix = getNetflix($_SESSION['username'], $_SESSION['access_token'], $_SESSION['access_token_secret'], $_SESSION['netflix_user_id']);
	    $queue = $netflix->getUserQueueDisc();
	    $queue->dequeue();
	}
	else if($action == 'login' || $action == null){
		fb($action, 'action is login or blank');
		//Check if we have everything we need in the session. If we do they are logged in already
		if(isLoggedIn()){
			return;
		}
		
		//If we know their username but nothing else we try to pull from database
		$username = mysql_real_escape_string($_REQUEST['username']);		
		if(empty($username)){
			$username = mysql_real_escape_string($_SESSION['username']);	
		}

		//If we have all their information (username, oauth_token, oauth_token_secret, netflix_user_id) in the database, log them in and show the main menu
		$userInfo = getUserFromDatabase($username);
		if($userInfo !== null){
			logUserIn($userInfo['username'], $userInfo['oauth_token'], $userInfo['oauth_token_secret'], $userInfo['netflix_user_id']);
			return;
		}
		//we have their username but no netflix information in the database, so they need to register
		else{		
			//Do we have the token and secret in the session? this happens if they are returning from netflix
			if(array_key_exists('oauth_token', $_SESSION) && strlen($_SESSION['oauth_token']) > 0 &&
				array_key_exists('oauth_token_secret', $_SESSION) && strlen($_SESSION['oauth_token_secret']) > 0){
				registrationCallback();
			}
			else{
				//No we dont have a token or secret for this user, begin the registration process
				beginRegistration($username);
			}
		}
	}
}

function registrationCallback(){
	$username = $_SESSION['username'];
	$oauth_token = $_SESSION['oauth_token'];
	$oauth_token_secret = $_SESSION['oauth_token_secret'];
	
	//We have a temp token and secret and a username, time to finalize it
	$netflix = getNetflix();
	$gotAccessToken = $netflix->getAccessToken($oauth_token, $oauth_token_secret);
	
	if($gotAccessToken === true){
		$access_token = $netflix->getToken();
		$access_token_key = $access_token->key;
		$access_token_secret = $access_token->secret;
		$netflix_user_id = $netflix->getUserId();
		
		//write it all to the database
		$query = "INSERT INTO user (`username`, `oauth_token`, `oauth_token_secret`, `netflix_user_id`)
				  VALUES ('$username', '$access_token_key', '$access_token_secret', '$netflix_user_id')";
		fb("Adding new user $username to database with token $access_token_key and secret $access_token_secret");
		mysql_query($query) or die("Could not execute query $query");
		
		//set up session so that they are logged in
		logUserIn($username, $access_token_key, $access_token_secret, $netflix_user_id);
				
		echo "Your account $username is now associated with netflix.<br />";
	}
	else{
		echo "There was an error getting the access token. <br />";
	}	
}

function logUserIn($username, $access_token_key, $access_token_secret, $netflix_user_id){
	$_SESSION['username'] = $username;
	$_SESSION['access_token'] = $access_token_key;
	$_SESSION['access_token_secret'] = $access_token_secret;
	$_SESSION['netflix_user_id'] = $netflix_user_id;
	
	unset($_SESSION['oauth_token']);
	unset($_SESSION['oauth_token_secret']);
	
	fb($_SESSION, 'session after logging user $username in');
}

function getUserFromDatabase($username){
	$userInfo = null;
	$oauth_token = null;
	$oauth_token_secret = null;
	$netflix_user_id = null;

	$query = "SELECT * FROM user where username='$username' LIMIT 1";
	$result = mysql_query($query) or die("Query failed $query");
	$userCount = mysql_num_rows($result);
	if($userCount > 0){
		$userInfo = mysql_fetch_assoc($result);
	}
	
	return $userInfo;
}

function isLoggedIn(){
	if(array_key_exists('username', $_SESSION) && strlen($_SESSION['username']) > 0 &&
		array_key_exists('access_token', $_SESSION) && strlen($_SESSION['access_token']) > 0 &&
		array_key_exists('access_token_secret', $_SESSION) && strlen($_SESSION['access_token_secret']) > 0 &&
		array_key_exists('netflix_user_id', $_SESSION) && strlen($_SESSION['netflix_user_id']) > 0){
		
		return true;
	}
	
	return false;
}

function getNetflix($username = null, $oauth_token = null, $oauth_token_secret = null, $netflix_user_id = null){
	$credentialsArray = getCredentials();

	if(!Netflix::checkCredentials($credentialsArray)){
		echo "Error in netflix consumer credentials<br />";
		return null;
	}
	
	$applicationName = $credentialsArray['application_name'];
	$consumerKey = $credentialsArray['consumer_key'];
	$consumerSecret = $credentialsArray['consumer_secret'];
	
	//Return a netflix object thats only good for getting a request token
	if($username == null && $oauth_token == null && $oauth_token_secret == null && $netflix_user_id == null){
		$netflix = new Netflix($consumerKey, $consumerSecret, $applicationName, null, null, null);
		return $netflix;
	}
	else if (strlen($username) > 0 && strlen($oauth_token) > 0 && strlen($oauth_token_secret) > 0 && strlen($netflix_user_id) > 0){
		$netflix = new Netflix($consumerKey, $consumerSecret, $applicationName, $oauth_token, $oauth_token_secret, $netflix_user_id);
		return $netflix;
	}	
	else{
		if(strlen($username) == 0){
			echo "Empty username provided to netflix factory.<br />";
		}
		if(strlen($oauth_token) == 0){
			echo "Empty oauth_token provided to netflix factory.<br />";
		}
		if(strlen($oauth_token_secret) == 0){
			echo "Empty oauth_token_secret provided to netflix factory. <br/>";
		}
		if(strlen($netflix_user_id) == 0){
			echo "Empty netflix_user_id provided to netflix factory. <br />";
		}
		
		return null;
	}
}

function getCredentials(){
	if(file_exists('credentials')){
		$credentials = explode('&', file_get_contents('credentials'));
		$credentialsArray = array();
		foreach($credentials as $credential){
			list($name, $value) = explode('=', $credential);
			$credentialsArray[trim($name)] = trim($value);
		}
	}

	return $credentialsArray;
}

?><html>
<head>
<title>OAuth Test Client</title>
</head>
<body>


	<div id="Main">
	<?php 
		doPost();
		
		if(isLoggedIn()){
			showMenu();
		}
		else{
			showLogin();
		}
	?></div>
	

	
	
	<div id="Debug">
	<?php 
		echo "<a href='?action=reset'>Reset session</a><br />";
	?>
	</div>
</body>
	
<footer style="width: 400px; margin:0pt auto; font-size:11px"><p>The code running this example can be downloaded from the PHP section of the OAuth google code project: <a href="http://code.google.com/p/oauth/">http://code.google.com/p/oauth/</a></footer>
</html>
